// pages/department/chat/chat.js

const app = getApp()
var timeId;
var socketTask;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    doctorInfo: {},
    chatList: [],
    inputValue: "",
    scrollIntoView: "",
  },

  onInput(event) {
    console.log("onInput", event);
    this.setData({
      inputValue: event.detail.value
    })
  },

  onSend() {
    const { userInfo, doctorInfo, chatList, inputValue, scrollIntoView } = this.data

    if (!inputValue) {
      return;
    }

    // 构造聊天消息对象
    var sendMsg = {
      content:        inputValue,
      sendTime:       new Date().getTime(),
      receiverAvater: doctorInfo.image,
      receiverId:     doctorInfo._id,
      receiverName:   doctorInfo.name,
      senderAvater:   userInfo.avater,
      senderId:       userInfo._id,
      senderName:     userInfo.realName
    };
    console.log("send msg", sendMsg);

    // 聊天消息保存到数据库
    wx.cloud.callFunction({
      name: 'add_chatMsg',
      data: {
        msg: sendMsg
      },
      success: res => {
        console.log("add chatMsg success", res);
      },
      fail: res => {
        console.log("add chatMsg fail", res);
      }
    });

    chatList.push(sendMsg);
    this.setData({
      chatList,
      inputValue: '',
    });

    this.scrollToBottom();

    socketTask.send({
      data: JSON.stringify(sendMsg)
    });
  },

  scrollToBottom() {
    // 获取最新消息的id
    const len = this.data.chatList.length;
    const sendTime = this.data.chatList[len - 1].sendTime;

    // 更新scroll-view的位置到最新记录
    this.setData({
      scrollIntoView: `msg${sendTime}`
    });

    console.log("scrollIntoView", this.data.scrollIntoView);
  },

  initWebSocket() {
    // 连接 websocket 服务器
    socketTask = wx.connectSocket({
      url: 'wss://websocket-prod-2ggbsy5aa8732cc5-1317335949.ap-shanghai.run.wxcloudrun.com',
      success: res => {
        console.log("connect success", res);
        wx.showToast({
          title: '连接成功'
        });
      },
      fail: res => {
        console.log("connect fail", res);
        wx.showToast({
          title: '连接失败'
        });
      }
    });

    // 监听收取数据
    socketTask.onMessage(res => {
      console.log('Received message:', res.data);

      var msg = JSON.parse(res.data);
      console.log("receive msg", msg);
      
      // 如果不是发给我的，则不接收
      if (msg.data.receiverId != this.data.userInfo._id)  return;

      var chatList = this.data.chatList;
      chatList.push(msg.data);
      this.setData({
        chatList: chatList
      });

      this.scrollToBottom();
      console.log("this charList", this.data.chatList);
    });

    socketTask.onClose(res => {
      console.log("websocket disconnect", res);
    });

    // 每隔30s发送一个心跳包
    timeId = setInterval(function(){
      socketTask.send({
        data: new Date().getTime()
      })
    }, 30000);
  },

  // 生命周期函数--监听页面加载
  onLoad(options) {
    let doctorInfo = JSON.parse(decodeURIComponent(options.doctorInfo));
    this.setData({
      doctorInfo: doctorInfo,
      userInfo: app.globalData.userInfo
    });

    wx.setNavigationBarTitle({
      title: doctorInfo.name,
    });

    // 获取聊天记录
    let that = this;
    const receiverId = this.data.doctorInfo._id;
    const senderId   = this.data.userInfo._id;
    wx.cloud.callFunction({
      name: 'get_chatMsg',
      data: {
        receiverId: receiverId,
        senderId:   senderId 
      },
      success: res => {
        console.log("get chatMsg success", res);
        that.setData({
          chatList: res.result.data
        }, function () {
          console.log("callback", that.data.chatList);
        });
        that.scrollToBottom();
      },
      fail: res => {
        console.log("get chatMsg fail", res);
      }
    });

    this.initWebSocket();
  },

  // 生命周期函数--监听页面初次渲染完成
  onReady() { },

  // 生命周期函数--监听页面显示
  onShow() { },

  // 生命周期函数--监听页面隐藏
  onHide() {  },

  // 生命周期函数--监听页面卸载
  onUnload() {
    console.log("chat.js onUnload");
    socketTask.close({
      success: res => {
        console.log("closeSocket success");
      },
      fail: res => {
        console.log("closeSocket fail");
      }
    });

    // 除定时器
    clearInterval(timerId);
   },

  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh() { },

  // 页面上拉触底事件的处理函数
  onReachBottom() { },

  // 用户点击右上角分享
  onShareAppMessage() { }
})